package com.lzy.search.controller;

import com.lzy.api.controller.user.HelloControllerApi;
import com.lzy.grace.result.GraceJSONResult;
import com.lzy.search.pojo.Stu;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.ElasticsearchClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class HelloController {

    @Autowired
    private ElasticsearchTemplate esTemplate;
    final static Logger logger = LoggerFactory.getLogger(HelloController.class);

    @GetMapping("hello")
    public Object hello() {
        return GraceJSONResult.ok();
    }

    @GetMapping("createIndex")
    public Object createIndex() {
        esTemplate.createIndex(Stu.class);
        return GraceJSONResult.ok();
    }

    @GetMapping("deleteIndex")
    public Object deleteIndex() {
        esTemplate.deleteIndex(Stu.class);
        return GraceJSONResult.ok();
    }

    @GetMapping("addDoc")
    public Object addDoc() {
        Stu stu = new Stu();
        stu.setStuId(1001L);
        stu.setName("lzy");
        stu.setAge(21);
        stu.setDesc("lzy的学生");
        stu.setMoney(100.2f);

        IndexQuery iq = new IndexQueryBuilder().withObject(stu).build();
        esTemplate.index(iq);
        return GraceJSONResult.ok();
    }

    @GetMapping("updateDoc")
    public Object updateDoc() {

        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("desc", "hello world");
        updateMap.put("age", 12);

        IndexRequest ir = new IndexRequest();
        ir.source(updateMap);

        UpdateQuery uq = new UpdateQueryBuilder()
                .withClass(Stu.class)
                .withId("1001")
                .withIndexRequest(ir)
                .build();

        esTemplate.update(uq);
        return GraceJSONResult.ok();
    }

    @GetMapping("getDoc")
    public Object getDoc(String id) {
        GetQuery gq = new GetQuery();
        gq.setId(id);
        Stu stu = esTemplate.queryForObject(gq, Stu.class);
        return GraceJSONResult.ok(stu);
    }

    @GetMapping("detDoc")
    public Object detDoc(String id) {
        esTemplate.delete(Stu.class, id);
        return GraceJSONResult.ok();
    }

}
